﻿/**
 * 
 */
package com.alstudio.ui.module.account;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.URLSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.ALModuleManager;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALPhoto;
import com.alstudio.module.xmpp.protocol.xmpp.data.ALXmppData;
import com.alstudio.module.xmpp.request.ALUiXmppRequestCreator;
import com.alstudio.module.xmpp.request.ALUiXmppRequestEvent;
import com.alstudio.module.xmpp.request.ALUiXmppRequestType;
import com.alstudio.pojo.ALXmppEvent;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.ui.module.main.MainActivity;
import com.alstudio.utils.android.keyboard.ALKeyBoardManager;
import com.alstudio.utils.android.net.http.UploadPhotoRequest;
import com.alstudio.utils.encode.ALDES;
import com.alstudio.utils.formater.string.StringUtils;
import com.alstudio.utils.formater.time.ALTimeUtils;
import com.alstudio.utils.log.ALLog;
import com.alstudio.utils.umeng.UmengUtils;
import com.alstudio.view.toast.MyToastUtil;
import com.alstudio.view.wheel.widget.OnWheelChangedListener;
import com.alstudio.view.wheel.widget.WheelView;
import com.alstudio.view.wheel.widget.adapters.ArrayWheelAdapter;
import com.alstudio.view.wheel.widget.adapters.NumericWheelAdapter;
import com.loovee.imaohu.R;

/**
 * 此界面用于输入个人资料，上传头像
 * 
 * @author Alonso Lee
 * 
 */
public class EnterPersonInfoActivity extends TitleBarActivity implements
		OnClickListener {

	private EditText etNick;
	private EditText etIntroductor, et_godaddy;
	private Button btBack, btDone;
	private LinearLayout btIcon, ll_man, ll_women;
	private ImageView imIcon;
	private CheckBox share_btn;

	private TextView etBirthday, etSex, tvUploadIcon,
			txt_agree_register_protocol;
	// 此变量用于标识是否已经在用户设定性别后打出toast的提示
	private boolean isShowSelectSexAlert = false;
	// 此变量用于标识是否已经显示上传头像奖励动画
	private boolean isShowUploadIconReward = false;

	private String register_pwd = "";
	private String register_invitecode = ""; // 优惠码

	// 注册超时时间设为15s
	private final long REGISTER_TIMEOUT = 30000;

	private ArrayList<ALPhoto> Photos;

	private String brithYears[];
	private String brithMonths[];
	private String brithDays[];

	private String brithyear = "";
	private String brithmonth = "";
	private String brithday = "";
	private String thisYear = "";

	private static String save_brithyear = "";
	private static String save_brithmonth = "";
	private static String save_brithday = "";

	private int indexY = 0;
	private int indexM = 0;
	private int indexD = 0;

	// 此对象用于暂存待上传的头像。上传成功后再传递到我的vcard中
	private ALPhoto tempPhoto;

	// 是否有sd卡
	private boolean isSdCardExist = false;

	// 注册成功
	private final int REGISTER_SUCCESS = 0;
	// 昵称有误
	private final int REGISTER_FAIL_500 = 500;
	// 邮箱有误
	private final int REGISTER_FAIL_501 = 501;
	// 密码太短
	private final int REGISTER_FAIL_502 = 502;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleBarContentView(R.layout.enter_person_info);
		setCenterTextViewMessage(R.string.TxtRegister);
		getintentData();
		findViews();
		init();
		initDefualtData();
	}

	// 获取Intent传输的数据
	private void getintentData() {
	}

	private void initDefualtData() {

		if (third_part_type != ALXmppData.LOGIN_TYPE_SYSTEM) {
			if (third_part_nickname != null) {
				etNick.setText(third_part_nickname);
			}

			if (third_part_birthday != null) {
				Date now = new Date(System.currentTimeMillis());

				int age = now.getYear() - third_part_birthday.getYear();
				if (age >= 0)
					etBirthday.setText(age + "");
			}

		}

	}

	protected void initData() {

		brithYears = ALTimeUtils.getDateYears();
		brithMonths = getResources().getStringArray(R.array.month);
		brithDays = getResources().getStringArray(R.array.day);

		indexY = brithYears.length - 1;
		indexM = brithMonths.length / 2;
		indexD = brithDays.length / 2;

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.et_birthday:
			// 选择生日
			ALKeyBoardManager.dismissKeyBoard(this);
			setBirthDay();
			break;
		case R.id.bt_Icon:
			// 选择头像
			// 弹出添添加相片dialog
			ALKeyBoardManager.dismissKeyBoard(this);
			showPhotoProcessDialog();

			break;
		case R.id.next_button:
			// 注册
			doRegister();
			break;
		}
	}

	private void findViews() {
		etNick = (EditText) findViewById(R.id.et_nickname);
		// 推荐人 暂时不用
		etBirthday = (TextView) findViewById(R.id.et_birthday);
		share_btn = (CheckBox) findViewById(R.id.share_btn);

		ll_women = (LinearLayout) findViewById(R.id.ll_women);
		ll_women.setOnClickListener(womenClickListener);
		ll_man = (LinearLayout) findViewById(R.id.ll_man);
		ll_man.setOnClickListener(menClickListener);
		// 头像布局
		btIcon = (LinearLayout) findViewById(R.id.bt_Icon);
		btIcon.setOnClickListener(this);
		// 头像图片
		imIcon = (ImageView) findViewById(R.id.imIcon);
		// 完成按钮
		btDone = (Button) findViewById(R.id.next_button);
		btDone.setOnClickListener(this);

		etBirthday.setOnClickListener(this);

		// 传递某个view给baseacitiviy用于显示popwindow
		setupView(this, getClass().getSimpleName());


		if (!isSdCardExist) {
			// 没有sd卡
			// imIcon.setBackgroundResource(R.drawable.avatar__);
		}

	}

	private void showTips() {

		txt_agree_register_protocol.setText(Html
				.fromHtml(getString(R.string.TxtAgreeRegisterProtocol)));
		txt_agree_register_protocol.setMovementMethod(LinkMovementMethod
				.getInstance());

		stripUnderlines(txt_agree_register_protocol);

	}

	private void stripUnderlines(TextView textView) {

		Spannable s = (Spannable) textView.getText();
		URLSpan[] spans = s.getSpans(0, s.length(), URLSpan.class);
		for (URLSpan span : spans) {
			int start = s.getSpanStart(span);
			int end = s.getSpanEnd(span);
			s.removeSpan(span);
			span = new URLSpanNoUnderline(span.getURL());
			s.setSpan(span, start, end, 0);
			s.setSpan(new BackgroundColorSpan(Color.TRANSPARENT), start, end, 0);
		}
		textView.setText(s);
	}

	private class URLSpanNoUnderline extends URLSpan {

		private String url = null;

		public URLSpanNoUnderline(String url) {
			super(url);
			this.url = url;
		}

		@Override
		public void updateDrawState(TextPaint ds) {
			super.updateDrawState(ds);
			ds.setUnderlineText(false);
			ds.setColor(Color.parseColor("#FF8500"));
		}

		@Override
		public void onClick(View widget) {
			if (url != null) {
				UmengUtils.markEvent(EnterPersonInfoActivity.this,
						UmengUtils.Event.VIEW_INSTRUCTION, null, null);
				// 跳转使用协议
				gotoUseProtocolActivity();
			}
		}

	}

	/**
	 * 跳转到使用协议页面
	 * 
	 * @author Alonso Lee
	 */
	private void gotoUseProtocolActivity() {

		// 使用协议
		// Intent intent = new Intent();
		// intent.setClass(this, WebViewActivity.class);
		// WebPageConfig config = new WebPageConfig();
		// config.setTitle(getString(R.string.string_use_protocol));
		// config.setUrl(App.mVersionConfig.USING_AGREEMENT
		// + App.getCurrentLanguage());
		// intent.putExtra("config", config);
		// // 启动页面跳转
		// startMyActivity(intent);
	}

	private void init() {
		Photos = new ArrayList<ALPhoto>();
	}

	private int select = 0;

	/**
	 * 设定生日
	 */
	private void setBirthDay() {

		initData();

		AlertDialog.Builder mBuilder = new AlertDialog.Builder(
				EnterPersonInfoActivity.this);
		// 不能用back销毁
		mBuilder.setCancelable(false);
		View contentView = ALLocalEnv.getLocalEnv().getGlobalLayoutInflater()
				.inflate(R.layout.brithdaywheelviewlayout, null);

		final WheelView year = (WheelView) contentView
				.findViewById(R.id.brith_year);
		final WheelView month = (WheelView) contentView
				.findViewById(R.id.brith_mouth);
		final WheelView day = (WheelView) contentView
				.findViewById(R.id.brith_day);

		String bry = "";
		String brm = "";
		String brd = "";
		String[] britydays = null;

		try {
			SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
			Date now = new Date();
			String nowdate = df.format(now);

			britydays = nowdate.split("/");
		} catch (Exception e) {
			e.printStackTrace();
		}

		try {
			if (britydays.length == 3) {

				bry = britydays[0];
				brm = britydays[1];
				brd = britydays[2];
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		if (!"".equals(save_brithyear) && !"".equals(save_brithmonth)
				&& !"".equals(save_brithday)) {

			indexY = getStringArrayIndex(brithYears, save_brithyear);
			indexM = getStringArrayIndex(brithMonths, save_brithmonth);
			indexD = getStringArrayIndex(brithDays, save_brithday);
		} else {
		}

		year.setViewAdapter(new DateArrayAdapter(this, brithYears, indexY));
		month.setViewAdapter(new DateArrayAdapter(this, brithMonths, indexM));
		day.setViewAdapter(new DateArrayAdapter(this, brithDays, indexD));

		year.setCurrentItem(indexY);
		month.setCurrentItem(indexM);
		day.setCurrentItem(indexD);

		updateDays(year, month, day);

		brithyear = brithYears[indexY];
		brithmonth = brithMonths[indexM];
		brithday = brithDays[indexD];

		thisYear = bry;

		year.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				updateDays(year, month, day);
				brithyear = brithYears[newValue];

			}
		});

		month.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				updateDays(year, month, day);
				brithmonth = brithMonths[newValue];

			}
		});

		day.addChangingListener(new OnWheelChangedListener() {

			@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
				// TODO Auto-generated method stub
				updateDays(year, month, day);
				brithday = brithDays[newValue];

			}
		});

		mBuilder.setView(contentView);

		mBuilder.setPositiveButton(R.string.BtnOk,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (brithyear.equals("") && brithmonth.equals("")
								&& brithday.equals("")) {
							brithyear = brithYears[indexY];
							brithmonth = brithMonths[indexM];
							brithday = brithDays[indexD];
						}

						int now = Integer.parseInt(thisYear);
						int select = Integer.parseInt(brithyear);

						if ((select - now) > 0) {
							// 选的不是今年了喔
							return;
						}

						save_brithyear = brithyear;
						save_brithmonth = brithmonth;
						save_brithday = brithday;

						String brith = save_brithyear + "-" + save_brithmonth
								+ "-" + save_brithday;
						ALLocalEnv.getLocalEnv().getMyProfile()
								.setBirthday(brith);

						etBirthday.setText("" + (now - select));

						dialog.dismiss();

					}
				});

		mBuilder.create().show();

	}

	/**
	 * 执行注册
	 */
	private void doRegister() {
		if (!ALLocalEnv.isNetworkConnected()) {
			return;
		}

		// 没有输入昵称
		if (etNick.getText().toString().trim().length() < 1) {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtEnterNick));
			return;
		}

		String nick = etNick.getText().toString().trim();

		String s = StringUtils.getNickBlockStr(getApplicationContext(), nick);
		if (!TextUtils.isEmpty(s)) {
			// 含有不合法的关键字
			String msg = String.format(
					getString(R.string.TxtBlockingKeywordAlert), s);
			MyToastUtil.getInstance().showToastOnCenter(msg);
			return;
		}

		// 生日不合法
		if (etBirthday.getText().toString().trim().length() == 0) {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtSelectBirthday));
			return;
		}

		if (select == 1) {
			ALLocalEnv.getLocalEnv().getMyProfile().setSex("male");
		} else if (select == 2) {
			ALLocalEnv.getLocalEnv().getMyProfile().setSex("female");
		} else {
			MyToastUtil.getInstance().showToastOnCenter(
					getString(R.string.TxtSelectSex));
			return;
		}

		if (!TextUtils.isEmpty(register_pwd)) {
			ALLocalEnv.getLocalEnv().getMyProfile().setPwd(register_pwd);
		}

		ALLocalEnv.getLocalEnv().getMyProfile()
				.setNick(etNick.getText().toString().trim());

		// App.isAlreadyLogoff = false;

		ALXmppData data = ALLocalEnv.getLocalEnv().createALXmppData();
		data.setMyRegisterInfo(ALLocalEnv.getLocalEnv().getMyProfile());
		if (third_part_type != ALXmppData.LOGIN_TYPE_SYSTEM
				&& !TextUtils.isEmpty(third_part_uid)) {
			// 第三方账号注册
			data.setThirdPartUid(third_part_uid);
			ALLog.d("第三方账号注册 token " + third_part_uid);
		} else {
			// 系统账号注册
			data.setEmail(ALLocalEnv.getLocalEnv().getMyProfile().getEmail());
			data.setPassword(ALLocalEnv.getLocalEnv().getMyProfile().getPwd());
			ALLog.d("系统账号注册email "
					+ ALLocalEnv.getLocalEnv().getMyProfile().getEmail()
					+ "密码 " + ALLocalEnv.getLocalEnv().getMyProfile().getPwd());

		}
		data.setThirdPartType(third_part_type);
		ALUiXmppRequestEvent event = ALUiXmppRequestCreator
				.creatorALUiXmppEvent(
						ALUiXmppRequestType.XMPP_REGISTER_REQUEST, data);

		ALModuleManager.getDefaultModuleManager().postEventToModuleManager(
				event);

		showLoadingProgress();

		ALKeyBoardManager.dismissKeyBoard(EnterPersonInfoActivity.this);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleRegisterEvent(com.alstudio.pojo
	 * .ALXmppEvent)
	 */
	@Override
	public void handleRegisterEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleRegisterEvent(data);
		ALLog.d("注册结果" + data.getResponseCode());
		switch (data.getResponseCode()) {
		case REGISTER_SUCCESS:
			// 注册成功
			ALLog.d("开始登陆");

			String jid = data.getJid();
			String pwd = data.getPwd();
			try {
				jid = ALDES.decryptDES(jid, ALXmppData.DES_KEY);
				pwd = ALDES.decryptDES(pwd, ALXmppData.DES_KEY);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ALUiXmppRequestCreator.postALUiXmppLoginEvent(jid, pwd);

			break;
		case REGISTER_FAIL_500:
			// 昵称有误
			break;
		case REGISTER_FAIL_501:
			// 邮箱有误
			break;
		case REGISTER_FAIL_502:
			// 密码太短
			break;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleLoginedEvent(com.alstudio.pojo
	 * .ALXmppEvent)
	 */
	@Override
	public void handleLoginedEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
//		Intent i = new Intent(this, MainActivity.class);
//		startActivity(i);
//		finish();
	}
	
	/* (non-Javadoc)
	 * @see com.alstudio.ui.base.BaseActivity#handleGetUserProfileEvent(com.alstudio.pojo.ALXmppEvent)
	 */
	@Override
	public void handleGetUserProfileEvent(ALXmppEvent data) {
		// TODO Auto-generated method stub
		super.handleGetUserProfileEvent(data);
		dismissLoadingProgress();
		Intent i = new Intent(this, MainActivity.class);
		startActivity(i);
		finish();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.BaseActivity#handleAuthFailedEvent(java.lang.String)
	 */
	@Override
	public void handleAuthFailedEvent(String errorMessage) {
		// TODO Auto-generated method stub
		super.handleAuthFailedEvent(errorMessage);
		ALLocalEnv.getLocalEnv().getMyAccount().setUserName("");
		ALLocalEnv.getLocalEnv().getMyAccount().setPassWord("");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#onGetProcessPhotosResult(java.lang
	 * .String, java.lang.String)
	 */
	@Override
	protected void onGetProcessPhotosResult(String path, String name) {
		// TODO Auto-generated method stub
		super.onGetProcessPhotosResult(path, name);
		Uri uri = Uri.fromFile(new File(path));
		ALLog.d("得到图片路径" + uri.toString());

		ALLocalEnv.getLocalEnv().getImageLoader()
				.displayImage(uri.toString(), imIcon);
		// 上传图片
		uploadPic(path);
		showLoadingProgress();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alstudio.ui.base.TitleBarActivity#handleUploadPicSuccess(com.alstudio
	 * .utils.android.net.http.UploadPhotoRequest, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	protected void handleUploadPicSuccess(UploadPhotoRequest sender,
			String pictureFileId, String thumbFileId) {
		// TODO Auto-generated method stub
		super.handleUploadPicSuccess(sender, pictureFileId, thumbFileId);
		dismissLoadingProgress();
		ALLog.d("图片上传成功 " + pictureFileId + "小兔 " + thumbFileId);
		tempPhoto = new ALPhoto();
		tempPhoto.setPicFileid(pictureFileId);
		tempPhoto.setThumbnailFileid(thumbFileId);
		ALLocalEnv.getLocalEnv().getMyProfile().getPhotos().add(0, tempPhoto);

	}

	private int getStringArrayIndex(String str[], String value) {

		int index = 0;

		for (int i = 0; i < str.length; i++) {

			if (value.equals(str[i]) || value == str[i]) {

				index = i;
			}
		}
		return index;
	}

	private class IconContent {
		private String path;
		private String viewId;

		/**
		 * @return the path
		 */
		public String getPath() {
			return path;
		}

		/**
		 * @param path
		 *            the path to set
		 */
		public void setPath(String path) {
			this.path = path;
		}

		/**
		 * @return the viewId
		 */
		public String getViewId() {
			return viewId;
		}

		/**
		 * @param viewId
		 *            the viewId to set
		 */
		public void setViewId(String viewId) {
			this.viewId = viewId;
		}

	}

	OnClickListener menClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			ALKeyBoardManager.dismissKeyBoard(EnterPersonInfoActivity.this);
			if (!isShowSelectSexAlert) {
				isShowSelectSexAlert = true;
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtSexAlert));
			}
			ll_man.setBackgroundResource(R.drawable.registration_gender_man);
			ll_women.setBackgroundResource(R.drawable.registration_gender_off);
			select = 1;
		}
	};
	OnClickListener womenClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			ALKeyBoardManager.dismissKeyBoard(EnterPersonInfoActivity.this);
			if (!isShowSelectSexAlert) {
				isShowSelectSexAlert = true;
				MyToastUtil.getInstance().showToastOnCenter(
						getString(R.string.TxtSexAlert));
			}
			ll_man.setBackgroundResource(R.drawable.registration_gender_off);
			ll_women.setBackgroundResource(R.drawable.registration_gender_woman);
			select = 2;
		}
	};

	/**
	 * Updates day wheel. Sets max days according to selected month and year
	 */
	void updateDays(WheelView year, WheelView month, WheelView day) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.YEAR,
				calendar.get(Calendar.YEAR) + year.getCurrentItem());
		calendar.set(Calendar.MONTH, month.getCurrentItem());

		int maxDays = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
		day.setViewAdapter(new DateNumericAdapter(this, 1, maxDays, calendar
				.get(Calendar.DAY_OF_MONTH) - 1));
		int curDay = Math.min(maxDays, day.getCurrentItem() + 1);
		day.setCurrentItem(curDay - 1, true);
	}

	/**
	 * Adapter for numeric wheels. Highlights the current value.
	 */
	private class DateNumericAdapter extends NumericWheelAdapter {
		// Index of current item
		int currentItem;
		// Index of item to be highlighted
		int currentValue;

		/**
		 * Constructor
		 */
		public DateNumericAdapter(Context context, int minValue, int maxValue,
				int current) {
			super(context, minValue, maxValue);
			this.currentValue = current;
			setTextSize(35);
		}

		@Override
		protected void configureTextView(TextView view) {
			super.configureTextView(view);
			if (currentItem == currentValue) {
				view.setTextColor(0xFF0000F0);
			}
			view.setTypeface(Typeface.SANS_SERIF);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, cachedView, parent);
		}
	}

	/**
	 * Adapter for string based wheel. Highlights the current value.
	 */
	private class DateArrayAdapter extends ArrayWheelAdapter<String> {
		// Index of current item
		int currentItem;
		// Index of item to be highlighted
		int currentValue;

		/**
		 * Constructor
		 */
		public DateArrayAdapter(Context context, String[] items, int current) {
			super(context, items);
			this.currentValue = current;
			setTextSize(35);
		}

		protected void configureTextView(TextView view) {
			super.configureTextView(view);
			if (currentItem == currentValue) {
				// view.setTextColor(0xFF0000F0);
			}
			view.setTypeface(Typeface.SANS_SERIF);
		}

		@Override
		public View getItem(int index, View cachedView, ViewGroup parent) {
			currentItem = index;
			return super.getItem(index, cachedView, parent);
		}
	}
}
